package com.entrogy.service.impl;

import com.entrogy.bean.*;
import com.entrogy.dao.AttendanceDao;
import com.entrogy.dao.AttendanceMapper;
import com.entrogy.service.AttendanceService;
import com.entrogy.service.ClassService;
import com.entrogy.timing.TimeUtils;
import com.entrogy.timing.TimingTaskService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.List;

@Service
@Transactional
public class AttendanceServiceImpl implements AttendanceService {

    private static final Logger logger = LoggerFactory.getLogger(AttendanceServiceImpl.class);

    @Autowired
    private AttendanceDao attendanceDao;
    @Autowired
    private ClassService classService;
    @Autowired
    private AttendanceMapper attendanceMapper;

    // 2、看是否存在某天的时间表，有的话就返回
    public JSONObject getDynArrange(String uId, String arrangeDate,int schoolCode) {
        JSONObject response = new JSONObject();
        try {
            ArrangeInformationEntity arrInfoBean = attendanceDao.getArrangeInfor(arrangeDate);
            if (arrInfoBean != null) {
                String tableName = arrInfoBean.getArrangeTable();
                JSONArray gradeList = getGradeList(tableName,schoolCode);
                /**
                 * 如果这个学校的这天作息时间为空 则去查询他的静态时间安排表，如果静态时间安排表中有时间 则新增到这天的时间作息表中
                 * 如果没有则不用管
                 */
                if(gradeList.size() == 0){
                    int curWeekNum = new TimeUtils().getWeekNum(arrangeDate);
                    List<ArrangeEntity> arrangeEntities = attendanceDao.getArrangeInfoBySCode(schoolCode);
                   if(arrangeEntities.size()>0){//有学校的时间安排表（新建的学校--有点逻辑问题，即其他学校已经创建了时间安排，在这中间有其他学校入住我们平台）
                       attendanceMapper.getStaticArrangeToDyn(tableName,curWeekNum,schoolCode);
                       attendanceMapper.insetDynCycle(arrInfoBean.getCycleTable(),schoolCode);
                   }
                    gradeList = getGradeList(tableName,schoolCode);
                }
                response.put("errcode", 0);
                response.put("errmsg", "查询成功");
                response.put("gradelist", gradeList);
                return response;
            } else {
                response.put("errcode", 1);
                response.put("errmsg", "没有" + arrangeDate + "的时间表");
                return response;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.put("errcode", 2);
        response.put("errmsg", "getDynArrange数据库查询错误");
        return response;
    }

    @Override
    public JSONObject addDynArrange(String uid, String arrangeDate,int schoolCode) {
        JSONObject response = new JSONObject();
        String[] yMd = arrangeDate.split("-");
        if (yMd[1].length() == 1)
            yMd[1] = "0" + yMd[1];
        if (yMd[2].length() == 1)
            yMd[2] = "0" + yMd[2];
        String tableArrange = "dyn_arrange" + yMd[0] + yMd[1] + yMd[2];
        String tableCycle = "dyn_cycle" + yMd[0] + yMd[1] + yMd[2];
        new TimingTaskService().createDynTable(arrangeDate, tableArrange, tableCycle, uid);
        JSONArray gradeList;
        try {
            gradeList = getGradeList(tableArrange,schoolCode);
            response.put("errcode", 0);
            response.put("errmsg", "增加成功");
            response.put("gradelist", gradeList);
            return response;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        response.put("errcode", 1);
        response.put("errmsg", "addDynArrange抛出异常");
        return response;
    }

    @Override
    public JSONObject updateDynArrange(String uid, String arrangeDate, JSONArray gradeList,int schoolCode) {
        System.out.println("arrangeDate" + arrangeDate);
        // System.out.println("gradeList" + gradeList.toString());
        String[] yMd = arrangeDate.split("-");
        if (yMd[1].length() == 1)
            yMd[1] = "0" + yMd[1];
        if (yMd[2].length() == 1)
            yMd[2] = "0" + yMd[2];
        String tableName = "dyn_arrange" + yMd[0] + yMd[1] + yMd[2];
        String tableCycle = "dyn_cycle" + yMd[0] + yMd[1] + yMd[2];
        // 创建返回的response对象
        JSONObject response = new JSONObject();
        response.put("errcode", 0);
        response.put("errmsg", "更新成功");
        try {
            for (int i = 0; i < gradeList.size(); i++) {
                JSONObject arrange = gradeList.getJSONObject(i);
                logger.info(uid + " update arrange in " + arrangeDate + " info:" + arrangeDate.toString());
                System.out.println("arrange" + arrange.toString());
                String course_id = arrange.getString("courseid");

                String time_slot1 = arrange.getString("afternoon");
                if (!time_slot1.isEmpty()) {
                    JSONObject timelist = JSONObject.fromObject(time_slot1);
                    String starttime = timelist.getString("starttime");
                    String endtime = timelist.getString("endtime");
                    if (!isNullStr(starttime) && !isNullStr(endtime))
                        time_slot1 = starttime.substring(0, starttime.length() - 3) + "-" + endtime.substring(0, starttime.length() - 3);
                    else
                        return null;
                }

                String time_slot2 = arrange.getString("evening");
                if (!time_slot2.isEmpty()) {
                    JSONObject timelist1 = JSONObject.fromObject(time_slot2);
                    String starttime1 = timelist1.getString("starttime");
                    String endtime1 = timelist1.getString("endtime");
                    if (!isNullStr(starttime1) && !isNullStr(endtime1))
                        time_slot2 = starttime1.substring(0, starttime1.length() - 3) + "-" + endtime1.substring(0, starttime1.length() - 3);
                    else
                        return null;
                }

                String time_slot3 = arrange.getString("night");
                if (!time_slot3.isEmpty()) {
                    JSONObject timelist2 = JSONObject.fromObject(time_slot3);
                    String starttime2 = timelist2.getString("starttime");
                    String endtime2 = timelist2.getString("endtime");
                    if (!isNullStr(starttime2) && !isNullStr(endtime2))
                        time_slot3 = starttime2.substring(0, starttime2.length() - 3) + "-" + endtime2.substring(0, starttime2.length() - 3);
                    else
                        return null;
                }

                int dayId = arrange.getInt("dayid");
                if (attendanceDao.setDynArrange(tableName, dayId, time_slot1, time_slot2, time_slot3, course_id,schoolCode)>0) {

                } else {
                    response.put("errcode", 1);
                    response.put("errmsg", "error");
                }
            }
            // 更新一下时间段表
            List<ArrangeEntity> dynArrangeBeanList = attendanceDao.getDynArrangeBeanList(tableName,schoolCode);
            for (ArrangeEntity arrBean : dynArrangeBeanList) {
                new TimingTaskService().updateDynCycle(tableCycle, arrBean);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.put("errcode", 1);
            response.put("errmsg", "error");
        }
        return response;
    }

    @Override
    public List<Integer> listAllDayType(String tableName, Integer schoolCode) {
        return attendanceMapper.listAllDayType(tableName, schoolCode);
    }

    // 获得接口中的gradelist项
    public JSONArray getGradeList(String tableName,int schoolCode) throws SQLException {
        JSONArray gradeList = new JSONArray();
        List<ArrangeEntity> arrBeanList = attendanceDao.getDynArrangeBeanList(tableName,schoolCode);
        for (ArrangeEntity dynArrBean : arrBeanList) {
            JSONObject gradeItem = new JSONObject();
            int courseId = dynArrBean.getCourseId();
            ClassEntity classEntity = classService.getClassById(courseId,schoolCode);
            if(classEntity != null){
                gradeItem.put("courseid", classEntity.getId());
                gradeItem.put("coursename", classEntity.getClassName());
            }
            // 当前的安排
            gradeItem.put("curarrange", getArrangeJson(dynArrBean, 1));
            JSONArray jStaticArrange = new JSONArray();
            List<ArrangeEntity> staticArrBeanList = attendanceDao.getStaticArrangeBeanList(courseId,schoolCode);
            for (ArrangeEntity staticArrBean : staticArrBeanList) {
                if (staticArrBean.getDayId() == dynArrBean.getDayId()) {
                    // 如果遍历到的静态安排和生成的动态安排冲突，使用动态安排
                    jStaticArrange.add(getArrangeJson(dynArrBean, 1));
                } else {
                    jStaticArrange.add(getArrangeJson(staticArrBean, 0));
                }
                // jStaticArrange.add(getArrangeJson(staticArrBean, 0));
            }
            gradeItem.put("staticarrange", jStaticArrange);
            gradeList.add(gradeItem);
        }
        return gradeList;
    }
    // 将ArrangeBean包装成json
    public JSONObject getArrangeJson(ArrangeEntity arrBean, int setFlag) {
        JSONObject arrangeJson = new JSONObject();
        int dayId = arrBean.getDayId();
        arrangeJson.put("setflag", setFlag);
        arrangeJson.put("dayid", dayId);
        try {
            DayTypeEntity dayType = attendanceDao.getDayTypeBeanById(dayId);
            arrangeJson.put("dayname", dayType.getDayName());
            arrangeJson.put("afternoon", getTimeSlotJobj(arrBean.getAfternoon()));
            arrangeJson.put("evening", getTimeSlotJobj(arrBean.getEvening()));
            arrangeJson.put("night", getTimeSlotJobj(arrBean.getNight()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return arrangeJson;
    }
    // 把时间段弄成json数组
    public JSONObject getTimeSlotJobj(String timeString) {
        JSONObject timeSlotJobj = new JSONObject();
        String[] timePoints = timeString.split("-");
        String[] hm = timePoints[0].split(":");
        timeSlotJobj.put("starttime", new TimeUtils().getStringTime(Integer.parseInt(hm[0]), Integer.parseInt(hm[1]), 0));
        hm = timePoints[1].split(":");
        timeSlotJobj.put("endtime", new TimeUtils().getStringTime(Integer.parseInt(hm[0]), Integer.parseInt(hm[1]), 0));
        return timeSlotJobj;
    }

    private boolean isNullStr(String string){
        return "null".equals(string);
    }
}
